package com.bp.hearthealth.pulse.lnapps.base

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.MutableLiveData
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_article.BpArticleDetailsActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_detect.BpHeartRateActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_splash.BpSplashActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_main.BpMainActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_dialog.BpGuideCamareDialog
import com.bp.hearthealth.pulse.lnapps.bp_utils.BPActivityCollector
import com.gyf.immersionbar.ImmersionBar
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import java.lang.ref.WeakReference
import java.lang.reflect.ParameterizedType


@SuppressLint("Registered")
open class BpBaseActivity<VDB : ViewDataBinding> : AppCompatActivity() {

    protected var activity: Activity? = null
    val permissionLiveData = MutableLiveData<Boolean>()
    var hasPermission: Boolean = false
    internal var _binding: VDB? = null
    val binding: VDB
        get() = _binding
            ?: throw IllegalStateException("Binding is null. Did you call setContentViewBinding() in onCreate()?")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activity = this
        setContentViewBinding()
    }

    private fun setContentViewBinding() {
        val bindingClass =
            (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<*>
        val method = bindingClass.getMethod(
            "inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java
        )
        _binding = method.invoke(null, layoutInflater, null, false) as VDB
        binding.lifecycleOwner = this
        setContentView(binding.root)
    }

    fun baseObserver() {
        permissionLiveData.observe(this) { permission ->
            hasPermission = permission
            if (permission) {
                startActivity(Intent(this, BpHeartRateActivity::class.java))
                LogUtil.i("savedInstanceState == null   permission: $permission")
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LogUtil.e("${activity?.javaClass?.simpleName} 销毁")
        if (activity?.javaClass?.simpleName != "BpSplashActivity") {
            AdMobNativeAdManager.setNativeAdListener(null)
        }
        AdMobInterstitialAdManager.setInterstitialAdListener(null)
        _binding = null
        activity = null
    }

    override fun setContentView(layoutResID: Int) {
        super.setContentView(layoutResID)
        initListener()
        initData()
        initImmersionBar()
    }

    override fun setContentView(layoutView: View) {
        super.setContentView(layoutView)
        initListener()
        initData()
        initImmersionBar()
    }

    open fun initData() {}

    open fun initListener() {}

    protected open fun initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).navigationBarColor(R.color.white).init()
    }

    fun requestPermission() {
        if (XXPermissions.isGranted(activity!!, Permission.CAMERA)) {
            permissionLiveData.value = true
        } else {
            checkCamera()
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (XXPermissions.isGranted(activity!!, Permission.CAMERA)) {
            LogUtil.i("onActivityResult")
            permissionLiveData.value = true
        }
    }

    private fun checkCamera() {
        XXPermissions.with(this).permission(Permission.CAMERA)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                    LogUtil.i("isReqested = true")
                    permissionLiveData.value = true
                }

                override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        val permissionDialog = BpGuideCamareDialog(activity!!)
                        permissionDialog.showDialog(UIHelperBp.getString(R.string._dialog_camare_str))
                        permissionDialog.setOnBtnClickLisener(object :
                            BpGuideCamareDialog.OnBtnClickListener {
                            override fun onBtnClick() {
                                XXPermissions.startPermissionActivity(
                                    activity!!, permissions
                                )
                            }
                        })
                    }
                }
            })
    }

    open fun startArticleActivity(title: String, drawableId: Int, fromType: String) {
        val intent = Intent(activity, BpArticleDetailsActivity::class.java)
        intent.putExtra("title", title)
        intent.putExtra("type", fromType)
        intent.putExtra("drawableId", drawableId)
        startActivity(intent)
    }
}